/*
  每人惠请求的总入口
 */


let tokenExpireCode = 401; //默认都给401
let requestSuccessCode = 200; //成功码给200
let statusCodeName = 'status'; // 状态码的值；
const config = require('../config/index')
const BaseRequestModel = {
  baseUrl: config.baseUrl,
  url: '', // 这里只认完整URL
  api: '',
  param: {}, // 参数
  method: 'POST', // 方法
  hideLoading: false, // loading
  checkUserId: true, // 检查登录
  head: {
    'Content-Type': 'application/json',
  },
  success: () => {},
  failed: () => {}
}
let innerApp = null
const init = function (app) {
  innerApp = app;
}

/**
 * 
 * @param {请求的参数} reqModel;自带了默认header;特殊需求的额外传
 * @param {如果需要自定义head;多传自定义的header过来} header 
 */
const mrjAsyncUploadReq = (reqModel, customerHeader) => {
  return new Promise((resolve, reject) => {
    const start = new Date().getTime();

    if (reqModel.hideLoading === false) {
      wx.showLoading({
        title: '加载中...',
      })
    }
    const header = {
      ...reqModel.head,
      ...customerHeader
    }
    console.log('url:', reqModel.url, 'method', reqModel.method, 'param:', reqModel.param, 'header:', header);

    wx.uploadFile({
      url: reqModel.url,
      filePath: reqModel.param.file,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      formData: {
        ...reqModel.param
      },
      success: res => {
        wx.hideLoading({
          success: (res) => {},
        })
        const end = new Date().getTime();
        console.log('url:' + reqModel.url + "耗时:" + (end - start) + 'ms');
        console.log('请求结果:', res.data);

        if (res.data[statusCodeName] === tokenExpireCode) // token 过期；触发登录
        {
          var app = getApp();
          app && app.loginInSystem && app.loginInSystem();
        } else if (res.data[statusCodeName] === requestSuccessCode) { // 正常返回

        } else { // 其他业务上的错误

        }
        resolve && resolve(res);
      },
      fail: f => {
        wx.hideLoading({
          success: (res) => {},
        })
        reject && reject(f)
      }
    })
  })
}
/**
 * 
 * @param {请求的参数} reqModel;自带了默认header;特殊需求的额外传
 * @param {如果需要自定义head;多传自定义的header过来} header 
 */
const mrjAsyncBaseReq = (reqModel, customerHeader) => {
  return new Promise((resolve, reject) => {
    const start = new Date().getTime();
    const header = {
      ...reqModel.head,
      Authorization: innerApp && innerApp.getToken && innerApp.getToken(),
      ...customerHeader
    }
    const param = {
      ...reqModel.param,
    }
    console.log('url:', reqModel.url, 'method', reqModel.method, 'param:', param, 'header:', header);
    if (reqModel.hideLoading === false) {
      wx.showLoading({
        title: '加载中...',
      })
    }
    wx.cloud.callFunction({
      name: 'main',
      data: {
        api: reqModel.api,
        data: param
      },
      success: res => {
        const {result} = res
        wx.hideLoading({
          success: r => {},
        })
        debugger
        const end = new Date().getTime();
        console.log('url:' + reqModel.url + "耗时:" + (end - start) + 'ms');
        console.log('请求结果:', result.data);
        // token 过期
        if (result[statusCodeName] === tokenExpireCode) {
          var app = innerApp;
          app && app.loginInSystem && app.loginInSystem();
        } else if (result[statusCodeName] === requestSuccessCode) { // 正常返回

        } else { // 其他业务上的错误

          wx.showToast({
            title: result.message,
            icon: 'none'
          })
        }
        resolve && resolve(result);
      },
      fail: f => {
        wx.hideLoading({
          success: (res) => {},
        })
        reject && reject(f)
      }
    })


    // wx.request({
    //   url: reqModel.url,
    //   method: reqModel.method,
    //   data: param,
    //   header: header,
    //   success: res => {
    //     wx.hideLoading({
    //       success: (res) => {},
    //     })
    //     const end = new Date().getTime();
    //     console.log('url:' + reqModel.url + "耗时:" + (end - start) + 'ms');
    //     console.log('请求结果:', res.data);
    //     // token 过期
    //     if (res.data[statusCodeName]  === tokenExpireCode) {
    //       var app = getApp();
    //       app && app.loginInSystem && app.loginInSystem();
    //     } else if (res.data[statusCodeName] === requestSuccessCode) { // 正常返回

    //     } else { // 其他业务上的错误

    //       wx.showToast({
    //         title: res.data.message,
    //         icon:'none'
    //       })
    //     }
    //     resolve && resolve(res);
    //   },
    //   fail: f => {

    //     wx.hideLoading({
    //       success: (res) => {},
    //     })
    //     reject && reject(f)
    //   }
    // })
  })
}




module.exports = {
  mrjAsyncBaseReq, //  基本请求
  mrjAsyncUploadReq, // 文件上传请求
  BaseRequestModel, // 基本请求对象
  init
};